package com.xiye.common.util;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @author 西野
 * @version V1.0
 * @title FileDownload.java
 * @package com.xiye.common.util
 * @description 文件处理
 * @date 2018-07-20
 */
public class FileDownload {

    /*
     * @Author 西野
     * @Date 2018-07-20 16:15:21
     * @Description 方法描述
     * @Param [response, filePath, fileName] filePath 文件完整路径(包括文件名和扩展名);fileName 下载后看到的文件名
     * @Return void
     */
    public static void fileDownload(final HttpServletResponse response, String filePath, String fileName) throws IOException {
        byte[] data = FileUtil.toByteArray2(filePath);
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream;charset=UTF-8");
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(data);
        outputStream.flush();
        outputStream.close();
        response.flushBuffer();
    }

}
